package com.lagou.client;

import com.alibaba.fastjson.JSON;
import com.lagou.service.*;
import com.sun.org.apache.xalan.internal.lib.NodeInfo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {

    public RpcConsumer(){
        //初始化zookeeper中服务器列表
        ZkProxy zkProxy = new ZkProxy();
        zkProxy.loadZkInfo();
    }

    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static RpcClientHandler userClientHandler;

    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    public Object createProxy(final Class<?> serviceClass,final String providerName){
        //借助JDK动态代理生成代理对象
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //（1）调用初始化netty客户端的方法


                //节点按照响应时间排序
                //时间不同，选择响应时间短的
                //时间相同，随机选择
                List<NodeContentInfo> childInfo = new ArrayList<>();
                List<String> childrenNode = ZkProxy.getClient().getChildren().forPath("/");
                for (String child : childrenNode) {
                    byte[] result = ZkProxy.getClient().getData().forPath("/" + child);
                    String json = new String(result);
                    System.out.println("服务器节点信息："+json);
                    NodeContentInfo nodeInfo = JSON.parseObject(json, NodeContentInfo.class);
                    childInfo.add(nodeInfo);
                }
                //根据响应时间排序
                Collections.sort(childInfo, (o1, o2) -> (int) (o1.getResponseTime() - o2.getResponseTime()));
                NodeContentInfo selectNode = childInfo.get(0);

                initClient(selectNode);
                System.out.println("客户端初始化");

                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setClassName(serviceClass.getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameters(args);
                rpcRequest.setParameterTypes(method.getParameterTypes());
                rpcRequest.setRequestId(UUID.randomUUID().toString());
                // 设置参数
                userClientHandler.setPara(rpcRequest);

                // 去服务端请求数据

                return executor.submit(userClientHandler).get();
            }
        });


    }



    //2.初始化netty客户端
    public static  void initClient(NodeContentInfo serverInfo) throws InterruptedException {
         userClientHandler = new RpcClientHandler();

        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast( new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                    }
                });

        bootstrap.connect(serverInfo.getIp(),serverInfo.getPort()).sync();

    }


}
